package com.example.bookmall.interceptors;


import com.example.bookmall.entity.Result;
import com.example.bookmall.utils.JwtUtil;
import com.example.bookmall.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
//把当前拦截器的对象放入到ioc容器中
//在所有请求前 把不符合的请求拦截起来
public class LoginInterceptors implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        //1.拿到令牌 request代表的是请求所以所有请求数据都在这里面
        String token = request.getHeader("Authorization");


        try {
            //从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);


           /* if (redisToken == null) {
                // 检查是否为购物相关接口
                String requestURI = request.getRequestURI();
                if (requestURI.startsWith("/cart/") ||
                        requestURI.startsWith("/orders/") ||
                        requestURI.startsWith("/address/")) {

                    // 设置响应状态码和提示信息
                    response.setStatus(403);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write("{\"code\":403,\"message\":\"请先注册或登录账号\"}");
                    return false;
                }

                // 其他接口允许匿名访问
                return true;
            }*/
            if(redisToken==null){
                //这就证明token已经失效了
                //抛出一个异常就回到下面的catch那里
                throw new RuntimeException();

            }

            Map<String,Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
            //http响应码为401
            response.setStatus(401);
            //不放行
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //可以用来清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
